package com.ki.erp.service.impl;

import com.ki.erp.constant.RedisConstant;
import com.ki.erp.operator.JwtOperator;
import com.ki.erp.operator.RedisOperator;
import com.ki.erp.req.PwdLoginReq;
import com.ki.erp.service.LoginService;
import com.ki.erp.vo.LoginUserVo;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class LoginServiceImpl implements LoginService {
    private @Resource AuthenticationManager authenticationManager;
    private @Resource RedisOperator redisOperator;
    private @Resource JwtOperator jwtOperator;

    @Override
    public HashMap<String, String> login(PwdLoginReq req) {

        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPwd()));
        if (authenticate == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        LoginUserVo loginUserVo = (LoginUserVo) authenticate.getPrincipal();
        String token = jwtOperator.generateToken(loginUserVo.getUser().getId());
        redisOperator.set(RedisConstant.TOKEN_PREFIX + loginUserVo.getUser().getId(), loginUserVo);
        HashMap<String, String> response = new HashMap<>();
        response.put("token", token);
        return response;
    }

    @Override
    public void logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUserVo loginUserVo = (LoginUserVo) authentication.getPrincipal();
        redisOperator.delete(RedisConstant.TOKEN_PREFIX + loginUserVo.getUser().getId());
    }
}
